package com.atguigu.gmall.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 基于死信的java配置类
 */
@Configuration
public class DeadLetterMqConfig {
    public static final String exchange_dead = "exchange.dead";
    public static final String routing_dead_1 = "routing.dead.1";
    public static final String routing_dead_2 = "routing.dead.2";
    public static final String queue_dead_1 = "queue.dead.1";
    public static final String queue_dead_2 = "queue.dead.2";

    //设置死信交换机
    @Bean
    public Exchange deadLetterExchange(){
        return ExchangeBuilder.directExchange(exchange_dead).build();
    }

    //设置死信队列
    @Bean
    public Queue deadLetterQueue(){
        Map<String, Object> arguments = new HashMap<>();
        //设置ttl 存货时间 时间:毫秒
        //arguments.put("x-message-ttl",1000 * 13);
        //设置过期转发的交换机
        arguments.put("x-dead-letter-exchange",exchange_dead);
        //设置过期转发的routingKey
        arguments.put("x-dead-letter-routing-key",routing_dead_2);
        return QueueBuilder.durable(queue_dead_1).withArguments(arguments).build();
    }

    //设置普通队列
    @Bean
    public Queue nQueue(){
        return QueueBuilder.durable(queue_dead_2).build();
    }

    //Binding 上面已经设置完所有的交换机,并且它们都在spring容器中
    //将死信队列和交换机进行绑定
    @Bean
    public Binding bindingDeadLetterQueueToDeadLetterExchange(
            @Qualifier(value = "deadLetterQueue") Queue deadLetterQueue,
            @Qualifier(value = "deadLetterExchange") Exchange deadLetterExchange
    ){
        return BindingBuilder.bind(deadLetterQueue).to(deadLetterExchange).with(routing_dead_1).noargs();
    }

    //将普通队列和交换机进行绑定
    @Bean
    public Binding bindingNQueueToDeadLetterExchange(
            @Qualifier(value = "nQueue") Queue nQueue,
            @Qualifier(value = "deadLetterExchange") Exchange deadLetterExchange
    ){
        return BindingBuilder.bind(nQueue).to(deadLetterExchange).with(routing_dead_2).noargs();
    }
 }
